package com.vicarica;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.WebContent;
import com.google.gdata.data.extensions.Recurrence;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.Reminder.Method;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.ServiceException;
import com.vicarica.entity.User;


public class GoogleCalendarUtils {


	  private static final String METAFEED_URL_BASE = "https://www.google.com/calendar/feeds/";

	  private static final String EVENT_FEED_URL_SUFFIX = "/private/full";

	  private static URL metafeedUrl = null;

	  private static URL eventFeedUrl = null;

	  private static CalendarEventEntry createEvent(CalendarService service,
	      String eventTitle, String eventContent, String recurData,
	      boolean isQuickAdd, WebContent wc) throws ServiceException, IOException {
	    CalendarEventEntry myEntry = new CalendarEventEntry();

	    myEntry.setTitle(new PlainTextConstruct(eventTitle));
	    myEntry.setContent(new PlainTextConstruct(eventContent));
	    myEntry.setQuickAdd(isQuickAdd);
	    myEntry.setWebContent(wc);

	    // If a recurrence was requested, add it. Otherwise, set the
	    // time (the current date and time) and duration (30 minutes)
	    // of the event.
	    if (recurData == null) {
	      Calendar calendar = new GregorianCalendar();
	      DateTime startTime = new DateTime(calendar.getTime(), TimeZone.getDefault());

	      calendar.add(Calendar.MINUTE, 30);
	      DateTime endTime = new DateTime(calendar.getTime(), 
	          TimeZone.getDefault());

	      When eventTimes = new When();
	      eventTimes.setStartTime(startTime);
	      eventTimes.setEndTime(endTime);
	      myEntry.addTime(eventTimes);
	    } else {
	      Recurrence recur = new Recurrence();
	      recur.setValue(recurData);
	      myEntry.setRecurrence(recur);
	    }

	    // Send the request and receive the response:
	    return service.insert(eventFeedUrl, myEntry);
	  }

	
	  private static CalendarEventEntry createRecurringEvent(
	      CalendarService service, String eventTitle, String eventContent, String recurData)
	      throws ServiceException, IOException {
	    // Specify a recurring event that occurs every Tuesday from May 1,
	    // 2007 through September 4, 2007. Note that we are using iCal (RFC 2445)
	    // syntax; see http://www.ietf.org/rfc/rfc2445.txt for more information.
	    //String recurData = "DTSTART;VALUE=DATE:20111118\r\n"
	      //  + "RRULE:FREQ=YEARLY;UNTIL=20171231\r\n";

	    return createEvent(service, eventTitle, eventContent, recurData, false,
	        null);
	  }


	  private static CalendarEventEntry addReminder(CalendarEventEntry entry, int numMinutes, Method methodType) throws ServiceException, IOException {
	    Reminder reminder = new Reminder();
	    reminder.setMinutes(numMinutes);
	    reminder.setMethod(methodType);
	    entry.getReminder().add(reminder);
	   
	    return entry.update();
	  }

	  public static void addAllBirthdays(Collection<User> users) {
		
	  CalendarService myService = new CalendarService("Birthday_Upload_Program");

	    // Set username and password from command-line arguments.
	    String userName = "xxxxx";
	    String userPassword = "xxxxx";

	    // Create the necessary URL objects.
	    try {
	      metafeedUrl = new URL(METAFEED_URL_BASE + userName);
	      eventFeedUrl = new URL(METAFEED_URL_BASE + userName + EVENT_FEED_URL_SUFFIX);
	    } catch (MalformedURLException e) {
	      // Bad URL
	      System.err.println("Uh oh - you've got an invalid URL.");
	      e.printStackTrace();
	      return;
	    }

	    try {
	    	
	      myService.setUserCredentials(userName, userPassword);

	      for (User user : users) {
	    	  addBirthday(myService, user.getName(), user.getFormattedBirthdayString());
	      }
	      
	    }
	    catch (IOException e) {
		      System.err.println("There was a problem communicating with the service.");
		      e.printStackTrace();
		    } catch (ServiceException e) {
		      System.err.println("The server had a problem handling your request.");
		      e.printStackTrace();
		}
	  }

	private static void addBirthday(CalendarService myService, String name, String birthdayString) throws ServiceException, IOException {
		
		 String recurData = "DTSTART;VALUE=DATE:"+birthdayString+"\r\n" + "RRULE:FREQ=YEARLY;UNTIL=20171231\r\n";
	      CalendarEventEntry recurringEvent = createRecurringEvent(myService, name+" Birthday", name+" Birthday.", recurData);
	      System.out.println("Successfully created recurring event " + recurringEvent.getTitle().getPlainText());
	      
	      recurringEvent = addReminder(recurringEvent, 15, Method.EMAIL);
	}
}
